<template>
  <div class="cascade-select-container">
    <!-- 选择器触发区域 -->
    <div class="selector-trigger" @click="openPopup">
      <div class="input-wrapper">
        <span class="label" :class="{ required: required }">{{ label }}</span>
        <div class="selected-text" :style="{ color: selectedText ? '#000' : '#cccccc' }">
          {{ selectedText || placeholder }}
        </div>
        <div class="address-arrow">
          <text class="gui-icons arrow-icon">&#xe601;</text>
        </div>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div class="popup-mask" v-if="showPopup" @click="closePopup"></div>

    <!-- 弹出选择框 -->
    <div class="popup-container" v-if="showPopup">
      <div class="popup-header">
        <div class="popup-title">{{ title || "请选择规格" }}</div>
        <div class="close-icon" @click="closePopup">×</div>
      </div>

      <!-- 只有在有两级规格时才显示标签页 -->
      <div class="popup-tabs" v-if="hasSecondLevel">
        <div
          class="tab-item"
          :class="{ active: currentStep === 0 }"
          @click="switchStep(0)"
        >
          {{ options[0].name || "无规格名" }}
        </div>
        <div
          class="tab-item"
          :class="{ active: currentStep === 1, disabled: !selectedFirstLevel }"
          @click="selectedFirstLevel && switchStep(1)"
        >
          {{ options[0].children ? options[0].children[0].name : "无规格名" }}
        </div>
      </div>

      <scroll-view class="popup-content" scroll-y>
        <!-- 第一级选择 -->
        <div v-if="currentStep === 0 || !hasSecondLevel">
          <div
            v-for="item in options"
            :key="item.value"
            class="option-item"
            :class="{
              active:
                selectedFirstLevel && selectedFirstLevel.value === item.value,
            }"
            @click="selectFirstLevel(item)"
          >
            <div class="option-text">{{ item.value }}</div>
            <i
              class="check-icon"
              v-if="
                selectedFirstLevel && selectedFirstLevel.value === item.value
              "
              >✓</i
            >
          </div>
        </div>

        <!-- 第二级选择 -->
        <div v-if="currentStep === 1 && selectedFirstLevel && hasSecondLevel">
          <div
            v-for="item in selectedFirstLevel.children"
            :key="item.value"
            class="option-item"
            :class="{
              active:
                selectedSecondLevel && selectedSecondLevel.value === item.value,
            }"
            @click="selectSecondLevel(item)"
          >
            <div class="option-text">{{ item.value }}</div>
            <i
              class="check-icon"
              v-if="
                selectedSecondLevel && selectedSecondLevel.value === item.value
              "
              >✓</i
            >
          </div>
        </div>
      </scroll-view>

      <div class="popup-footer">
        <div class="price-info" v-if="selectedSpecData">
          <div class="spec-name">
            <text class="spec-label">已选：</text>
            <text class="spec-value">{{ selectedText }}</text>
          </div>
          <div class="price-container">
            <text class="factory-price" v-if="selectedSpecData.discount_price"
              >￥{{ selectedSpecData.discount_price }}</text
            >
            <text class="discount-price" v-if="selectedSpecData.factory_price"
              >￥{{ selectedSpecData.factory_price }}</text
            >
          </div>
        </div>
        <button
          class="confirm-btn"
          :disabled="!isSelectionComplete"
          @click="confirmSelection"
        >
          确认选择
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";

// 定义组件属性
const props = defineProps({
  // 选择器标签
  label: {
    type: String,
    default: "规格",
  },
  // 是否必选
  required: {
    type: Boolean,
    default: false,
  },
  // 占位提示文字
  placeholder: {
    type: String,
    default: "请选择商品规格",
  },
  // 弹窗标题
  title: {
    type: String,
    default: "请选择商品后再选规格",
  },
  // 选项数据
  options: {
    type: Array,
    default: () => [],
  },
  // 已选中的规格数据（双向绑定）
  modelValue: {
    type: String,
    default: "",
  },
});

// 定义事件
const emit = defineEmits(["update:modelValue", "change"]);

// 弹窗显示状态
const showPopup = ref(false);
// 当前选择步骤：0-选择第一级，1-选择第二级
const currentStep = ref(0);
// 已选择的第一级选项
const selectedFirstLevel = ref(null);
// 已选择的第二级选项
const selectedSecondLevel = ref(null);

// 判断是否有第二级规格
const hasSecondLevel = computed(() => {
  return (
    props.options.length > 0 &&
    props.options[0].children &&
    props.options[0].children.length > 0
  );
});

// 根据ID查找并选中对应的选项
const findAndSelectOption = (id) => {
  if (!props.options || props.options.length === 0) return;
  
  // 查找包含此ID的选项
  for (const firstLevel of props.options) {
    if (firstLevel.data && firstLevel.data.id === id) {
      // 找到第一级
      selectedFirstLevel.value = firstLevel;
      return;
    }
    
    // 查找第二级
    if (firstLevel.children && firstLevel.children.length > 0) {
      for (const secondLevel of firstLevel.children) {
        if (secondLevel.data && secondLevel.data.id === id) {
          // 找到第二级，需要同时设置第一级和第二级
          selectedFirstLevel.value = firstLevel;
          selectedSecondLevel.value = secondLevel;
          return;
        }
      }
    }
  }
};

// 监听modelValue变化，回填已选择的值
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      // 遍历所有规格选项，找到对应的ID
      findAndSelectOption(newVal);
    } else {
      // 如果modelValue被清空，也清空已选择的值
      selectedFirstLevel.value = null;
      selectedSecondLevel.value = null;
    }
  },
  { immediate: true, deep: true }
);



// 监听options变化，当options加载完成后，尝试回显数据
watch(
  () => props.options,
  (newOptions) => {
    if (newOptions && newOptions.length > 0 && props.modelValue) {
      // 当options数据加载完成并且有modelValue值时，进行回显
      findAndSelectOption(props.modelValue);
    }
  },
  { deep: true }
);

// 计算已选择的文本
const selectedText = computed(() => {
  if (hasSecondLevel.value) {
    // 有两级规格的情况
    if (selectedFirstLevel.value && selectedSecondLevel.value) {
      return `${selectedFirstLevel.value.value}   ${selectedSecondLevel.value.value}`;
    }
  } else {
    // 只有一级规格的情况
    if (selectedFirstLevel.value) {
      return `${selectedFirstLevel.value.value}`;
    }
  }
  return "";
});

// 判断选择是否完成
const isSelectionComplete = computed(() => {
  if (hasSecondLevel.value) {
    // 有两级规格时，需要两级都选择
    return selectedFirstLevel.value && selectedSecondLevel.value;
  } else {
    // 只有一级规格时，只需选择第一级
    return selectedFirstLevel.value !== null;
  }
});

// 选择第一级
const selectFirstLevel = (item) => {
  selectedFirstLevel.value = item;

  if (hasSecondLevel.value) {
    // 有第二级规格，清空第二级选择并进入第二级选择
    selectedSecondLevel.value = null;
    currentStep.value = 1;
  } else {
    // 没有第二级规格，直接完成选择
    // 不需要切换步骤，保持在第一级
  }
};

// 选择第二级
const selectSecondLevel = (item) => {
  selectedSecondLevel.value = item;
};

// 切换选择步骤
const switchStep = (step) => {
  currentStep.value = step;
};

const selectedSpecData = computed(() => {
  if (hasSecondLevel.value) {
    return selectedSecondLevel.value?.data || null;
  } else {
    return selectedFirstLevel.value?.data || null;
  }
});


// 确认选择
const confirmSelection = () => {
  if (isSelectionComplete.value) {
    let result;

    if (hasSecondLevel.value) {
      // 有第二级规格，返回第二级的数据
      result = selectedSecondLevel.value.data;
    } else {
      // 只有一级规格，直接返回第一级的数据
      result = selectedFirstLevel.value.data;
    }

    // 更新双向绑定的值
    emit("update:modelValue", result.id);
    // 发出change事件
    emit("change", result);
    // 关闭弹窗
    closePopup();
  }
};

// 打开弹窗
const openPopup = () => {
  showPopup.value = true;
  // 默认显示第一级
  currentStep.value = 0;
};

// 关闭弹窗
const closePopup = () => {
  showPopup.value = false;
};
</script>

<style scoped>
.cascade-select-container {
  position: relative;
  width: 100%;
  font-size: 28rpx;
}

.selector-trigger {
  width: 100%;
}

.input-wrapper {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #ebeef5;
  position: relative;
}

.label {
  width: 180rpx;
  font-size: 28rpx;
  color: #333;
}

.required::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4rpx;
}

.selected-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: end;
  font-weight: bolder;
}

.selected-text:empty {
  color: #cccccc;
}

.address-arrow {
  width: 40rpx;
  text-align: right;
}

.arrow-icon {
  color: #ccc;
  font-size: 32rpx;
}

/* 弹出层样式 */
.popup-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.popup-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 1000;
  animation: slideUp 0.3s ease;
  display: flex;
  flex-direction: column;
  max-height: 70vh;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #ebeef5;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-icon {
  font-size: 40rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-tabs {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #1989fa;
  font-weight: bold;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #1989fa;
}

.tab-item.disabled {
  color: #ccc;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 30rpx;
  max-height: 50vh;
}

.option-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #ebeef5;
}

.option-item.active {
  color: #1989fa;
}

.option-text {
  font-size: 28rpx;
}

.check-icon {
  font-size: 40rpx;
  font-weight: bold;
}

.popup-footer {
  padding: 20rpx 30rpx;
  border-top: 1px solid #ebeef5;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.confirm-btn:disabled {
  background-color: #cccccc;
}

.price-info {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
}

.spec-name {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.spec-label {
  font-size: 26rpx;
  color: #666;
}

.spec-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.price-container {
  display: flex;
  align-items: center;
}

.factory-price {
  font-size: 32rpx;
  color: #ff6600;
  font-weight: bold;
}

.discount-price {
  font-size: 26rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}
</style>
